<template>
    <div>
        <!--1.条件查询表单-->
        {{studentSearch}}
        <el-form :inline="true" :model="studentSearch" class="demo-form-inline"  style="margin-top: 20px" align="left">
            <el-form-item>
                <el-input v-model="studentSearch.sname" placeholder="学生姓名："></el-input>
             </el-form-item>

                <el-form-item>
                <el-input v-model="studentSearch.addr" placeholder="地址："></el-input>
                </el-form-item>

                <el-select v-model="studentSearch.cid" placeholder="所在班级：">
                    <el-option label="所有班级" :value="0"></el-option>
                    <el-option :label="c.cname" v-for=" c in classes" :value="c.cid"></el-option>

                </el-select>

            <el-form-item>
                <el-button type="primary" @click="search" style="margin-left: 10px;" icon="el-icon-search">查询</el-button>
                <el-button type="success" @click="addStudent" icon="el-icon-plus">添加</el-button>
                <el-button type="danger" @click="handleDelete" icon="el-icon-delete">批量删除</el-button>
            </el-form-item>
        </el-form>

        <!--定义编辑学生的对话框-->

        <el-dialog :title="student.sid ? '修改学生':'添加学生'" :visible.sync="dialogFormVisible" :close-on-click-modal="false">
            student：{{student}}
            <el-form :model="student" :rules="rules" ref="studentRule">
                <el-form-item label="学生姓名" :label-width="formLabelWidth" align="left" prop="sname">
                    <el-input v-model="student.sname" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="性别" :label-width="formLabelWidth" align="left" prop="sex">
                    <el-radio v-model="student.sex" label="男">男</el-radio>
                    <el-radio v-model="student.sex" label="女">女</el-radio>
                </el-form-item>

                <el-form-item label="年龄" :label-width="formLabelWidth" prop="age">
                    <el-input v-model.number="student.age" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="地址" :label-width="formLabelWidth" prop="addr">
                    <el-input v-model="student.addr" autocomplete="off"></el-input>
                </el-form-item>

                <el-form-item label="所在班级" :label-width="formLabelWidth" align="left" prop="cid">
                    <el-select v-model="student.cid" placeholder="请选择班级" >
                        <el-option :label="c.cname" v-for="c in classes" :value="c.cid" ></el-option>
<!--                                                <el-option label="区域二" value="beijing"></el-option>-->
                    </el-select>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>

        <!--2.学生列表-->
        <el-table
                :data="students"
                @selection-change="handleSelectionChange"
                style="width: 100%">

            <el-table-column
                    type="selection"
                    width="55">
            </el-table-column>

            <el-table-column
                    label="学号"
                    prop="sid"
                    align="center"
                    >

            </el-table-column>
            <el-table-column
                    label="姓名"
                    prop="sname"
                    align="center"
            >
            </el-table-column>
            <el-table-column
                    label="性别"
                    prop="sex"
                    align="center">
            </el-table-column>
            <el-table-column
                    label="年龄"
                    prop="age"
                    align="center">
            </el-table-column>
            <el-table-column
                    label="地址"
                    prop="addr"
                    align="center">
            </el-table-column>
            <el-table-column
                    label="班级"
                    prop="cname"
                    align="center">
            </el-table-column>
            <el-table-column label="操作" align="center"
            >
                <template slot-scope="scope">
                    <el-button
                            size="mini"
                            @click="handleEdit(scope.row)">编辑</el-button>
                    <el-button
                            size="mini"
                            type="danger"
                            @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <!--分页导航-->
        <el-pagination
                style="margin-top: 20px"
                align="right"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                :current-page="page"
                :page-sizes="[7, 14, 21, 28]"
                :page-size="pageSize"
                layout="total, sizes, prev, pager, next, jumper"
                :total="total"


        >
        </el-pagination>



    </div>

</template>

<script>
    export default {
        name: "list",

        data(){
            // 自定义验证规则
            let ageValiator = (rule,value,callback)=>{
                // 1.1 验证非空a
                if (!value) {
                    callback(new Error('年龄不为空'))
                }else if (!Number.isInteger(value)) {
                    callback(new Error('年龄必须为整数'))
                }else if (!(value > 0 && value < 150)) {
                    callback(new Error('请输入范围正确的年龄'))
                } else {
                    callback();
                }
            }
            return {
                students: [],
                page:1,             // 当前页
                pageSize:7,         // 每页大小
                total:100,          //总记录数
                studentSearch:{}, // 代表当前查询的学生
                classes:[],         // 班级列表
                dialogFormVisible:false,    // 控制对话框的显示与隐藏
                formLabelWidth:'100px',
                student:{},         // 用于编辑的学生（add/update）
                successMessage:'',
                multipleSelection: [], // 所选择的学生对象数组
                ids: [],                // 一个或多个选择的学生sid
                rules:{
                    sname: [
                        { required: true, message: '请输入学生姓名', trigger: 'blur'},
                    ],
                    sex: [
                        { required: true, message: '请输入学生性别', trigger: 'change'},
                    ],
                    age: [
                        { validator: ageValiator, trigger: 'blur'},
                    ],
                    addr: [
                        { required: true, message: '请输入学生地址', trigger: 'blur'},
                    ],
                    cid: [
                        { required: true, message: '请输入学生班级', trigger: 'change'},
                    ]

                },
            }

        },
        created() {
            // console.log("当前修改了list.vue文件~")
            // this.findStudents()    // 查询所有学生
            // 1. 进行分页查询
            // this.findByPage();

            // 3.条件查询带分页
            this.search();

            // 2. 查询班级列表
            this.findClasses();


        },
        methods:{
            // 1. 查询所有学生
            findStudents(){
                this.$axios.get("/student?cmd=list").then(resp=>{
                    this.students = resp.data;
                    console.log("data:",resp.data)
                })
            },

            // 2. 页大小 （pageSize）改变触发
            handleSizeChange(pageSize) {
                console.log(`每页 ${pageSize} 条`);
                this.pageSize = pageSize;
                // this.findByPage();
                this.search();
            },
            // 3. 当前页改变时触发（page）
            handleCurrentChange(page) {
                console.log(`当前页: ${page}`);
                this.page = page;
                // this.findByPage();
                this.search();
            },
            // 4. 分页查询
            findByPage() {
                this.$axios.get(`/student?cmd=findByPage&page=${this.page}&pageSize=${this.pageSize}`).then(resp=>{
                    // 2.1 为学生列表赋值
                    this.students = resp.data.rows
                    // 2.2 为总记录数赋值
                    this.total = resp.data.total
                })
            },
            // 5. 查询班级列表
            findClasses(){
                this.$axios.get("/classes").then(resp=>{
                    this.classes = resp.data
                })
            },

            // 6. 条件查询带分页
            search () {
                let stud = JSON.stringify(this.studentSearch)
                console.log("stud: ",stud)
                this.$axios.post(`/student?cmd=search&page=${this.page}&pageSize=${this.pageSize}`,
                    "data="+stud)
                    .then(resp=>{
                        this.total = resp.data.total;
                        this.students = resp.data.rows;
                        console.log("resp:",resp)
                    })
            },

            // 7. 添加学生
            addStudent(){
                // 清空对象
                this.student = {};
                // 显示添加框
                this.dialogFormVisible=true;

            },

            // 7.1 保存学生(包含添加和修改）
            save(){
                this.$refs['studentRule'].validate((valid)=>{
                    let _this = this;
                    if (valid) {
                        let url = "/student?cmd=save"
                        if (this.student.sid) {
                            url = "/student?cmd=update"
                        }
                        this.$axios.post(url, "data=" + JSON.stringify(this.student)).then(({data})=>{
                            console.log("data:", data);
                            if (data.code == 0) {
                                this.$message({
                                    message: `${this.student.sid ? '修改成功' : '添加成功'}`,
                                    type: 'success',
                                    onClose(){
                                        // 1. 刷新页面
                                        _this.search();
                                        // 2. 关闭对话框
                                        _this.dialogFormVisible = false;
                                    }
                                })
                            }
                        });
                    }else {
                        alert(this.title='有验证未通过的表单')
                    }
                })

            },

            // 8. 修改学生
            handleEdit(row){
                // 8.1 弹出修改框
                this.dialogFormVisible = true;
                // 8.2 显示数据
                this.student = row;
            },

            // 9. 删除学生
            handleDelete(index,row){
                let _this = this;
                // console.log(index, " ----> " , row)
                if (row) {
                    //进行单个删除
                    this.ids = [row.sid]
                } else {
                    //进行批量删除
                    this.ids = this.multipleSelection.map(m=>m.sid)
                }
                // console.log("ids ----->" ,this.ids)
                // 第二步： 放松delete异步请求
                this.$confirm(`你真的要删除编号为${this.ids}的学生吗？`, '温馨提示',{
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    // 点击了“确定” 按钮，此时向后端发送请求
                    this.$axios.get(`/student?cmd=delete&ids=${this.ids}`).then(({data})=>{
                        if (data.code === 0) {
                            this.$message({
                                type: 'success',
                                message: '删除成功!',
                                onClose(){
                                    _this.search()
                                }
                            });
                        }
                    })

                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });

            },

            // 10. 选中框
            handleSelectionChange(val) {
                this.multipleSelection = val;
                // console.log("选择的编号对象----->",this.multipleSelection)
            },
        },

    }
</script>

<style scoped>

</style>